package com.wine.exam.service.impl;

import java.util.*;
import java.util.stream.Collectors;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wine.common.utils.DateUtils;
import com.wine.common.utils.StringUtils;
import com.wine.exam.domain.Paper;

import com.wine.exam.domain.PaperQuestion;
import com.wine.exam.domain.Question;
import com.wine.exam.dto.PaperDto;
import com.wine.exam.mapper.PaperMapper;
import com.wine.exam.mapper.PaperQuestionMapper;
import com.wine.exam.mapper.QuestionMapper;
import com.wine.exam.service.IPaperService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


/**
 * 试卷Service业务层处理
 *
 * @author wine
 * @date 2022-10-13
 */
@Service


public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements IPaperService {

    @Autowired
    private PaperMapper PaperMapper;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 根据paper 获取到属于这张试卷的题目，
     */
    private List<Question> getQuestions(Paper paper) {
        if (StringUtils.isNull(paper)) {
            return null;
        }
        LambdaQueryWrapper<PaperQuestion> paperQuestionQueryWrapper = new LambdaQueryWrapper<>();
        paperQuestionQueryWrapper.eq(PaperQuestion::getPaperId, paper.getPaperId());
        //            查出所有该试卷的 问题的id
        Long[] questionIds = paperQuestionMapper.selectQuestionListByPaperId(paper.getPaperId());
        if (questionIds.length > 0) {
// 根据问题的ids 查出问题详细
            List<Question> questions = questionMapper.selectBatchIds(Arrays.asList(questionIds));
            return questions;
        } else {
            return null;
        }
    }


    /**
     * 根据试卷名称，学科，开始，结束时间 可选查询 试卷
     *
     * @param paperDto
     * @return
     */
    @Override
    public Page<Paper> pageQueryList(PaperDto paperDto) {


        Page<Paper> page = new Page<>();
        page.setCurrent(paperDto.getPageNum());
        page.setSize(paperDto.getPageSize());

        LambdaQueryWrapper<Paper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(
                paperDto.getPaperName()),
                Paper::getPaperName,
                paperDto.getPaperName());
        queryWrapper.eq(StringUtils.isNotEmpty(paperDto.getSubjectId()),
                Paper::getPaperName,
                paperDto.getSubjectId());
//                如果apply，apply 两个的话拼接的sql会有问题
        System.out.println(paperDto.getLimitStartTime());
        System.out.println(paperDto.getLimitEndTime());
//        为什么这里是false 还会拼接 草
//        这里还是有问题，结束时间小于  应该是有的
        System.out.println(StringUtils.isNotEmpty(paperDto.getLimitEndTime()));
        queryWrapper.ge(StringUtils.isNotEmpty(paperDto.getLimitStartTime()),
                Paper::getLimitStartTime,
                paperDto.getLimitStartTime());
        queryWrapper.le(StringUtils.isNotEmpty(paperDto.getLimitEndTime()),
                Paper::getLimitEndTime,
                paperDto.getLimitEndTime());
        Page<Paper> list = PaperMapper.selectPage(page, queryWrapper);
        return list;
    }


    /**
     * 获取试卷单表详情 根据paperId
     *
     * @param paperId
     * @return
     */
    @Override
    public Paper getPaper(Long paperId) {
        return PaperMapper.selectById(paperId);
    }

    /**
     * 无答案
     *
     * @param paper      试卷
     * @param hasCorrect true : 有答案和信息  false 无答案
     * @return
     */
    @Override
    public List<Question> getQuestionsByPaper(Paper paper, Boolean hasCorrect) {
        if (hasCorrect) { // 有答案
            return this.getQuestions(paper);
        } else {

            List<Question> questions = this.getQuestions(paper);
            System.out.println(questions);

            if (Objects.isNull(questions) || questions.size() <= 0) {
                return null;
            } else {
                for (Question i : questions) {
                    i.setCorrect(null);
                    i.setInfo(null);
                }
                return questions;
            }

        }

    }


    /**
     * 查询试卷详情：包含试题
     *
     * @param paperId    试卷主键
     * @param hasCorrect true : 有答案和信息  false 无答案
     * @return
     */
    @Override
    public Map<String, Object> getInfo(Long paperId, Boolean hasCorrect) {
        HashMap<String, Object> paperAndQuestion = new HashMap<>();
        Paper paperInfo = this.getPaper(paperId);
        paperAndQuestion.put("paper", paperInfo);
        if (hasCorrect) {
            List<Question> questionsByPaper = this.getQuestionsByPaper(paperInfo, true);
            paperAndQuestion.put("paperAndQuestion", questionsByPaper);
        } else {
            List<Question> questionsByPaper = this.getQuestionsByPaper(paperInfo, false);
            paperAndQuestion.put("paperAndQuestion", questionsByPaper);
        }
        return paperAndQuestion;
    }


 /*   @Override
    public Map<String, Object> getInfo(Long paperId) {


//        获取试卷的基本信息
        Paper paper = PaperMapper.selectById(paperId);
        HashMap<String, Object> paperAndQuestion = new HashMap<>();
        paperAndQuestion.put("paper", paper);
//        判断是否根据这个id查出来了是否有这张试卷
        if (!ObjectUtils.isEmpty(paper)) {
            //根据查出来的试卷的 id 查出所有问题的id
            LambdaQueryWrapper<PaperQuestion> paperQuestionQueryWrapper = new LambdaQueryWrapper<>();
            paperQuestionQueryWrapper.eq(PaperQuestion::getPaperId, paperId);
//            查出所有该试卷的 问题的id
            Long[] questionIds = paperQuestionMapper.selectQuestionListByPaperId(paperId);
            if (questionIds.length > 0) {
// 根据问题的ids 查出问题详细
                List<Question> questions = questionMapper.selectBatchIds(Arrays.asList(questionIds));
//                List<Question> questions = questionMapper.selectList(new QueryWrapper<>());
                System.out.println("questions" + questions);
                paperAndQuestion.put("questionList", questions);
            } else {
                paperAndQuestion.put("questionList", null);
            }
        }
        System.out.println("paperAndQuestion" + paperAndQuestion);
        return paperAndQuestion;
    }*/


    /**
     * 修改试卷状态
     *
     * @param paperId 试卷主键
     * @param status  状态码
     * @return
     */
    @Override
    public int updateStatus(Long paperId, String status) {

        return PaperMapper.updateStatus(paperId, status);
    }


    /**
     * 根据试卷id 删除试卷和 属于这个试卷的题目（关联表里的）
     * TODO 当前试卷的删除是逻辑删除，但是关联表里是真实删除，考虑
     *
     * @param paperId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delById(Long paperId) {

        int row = PaperMapper.deleteById(paperId);


        LambdaQueryWrapper<PaperQuestion> query = new LambdaQueryWrapper<>();
        query.eq(PaperQuestion::getPaperId, paperId);
//        影响行数大于0 说明删除了paper里的数据，再来删除，否则不走
        List<PaperQuestion> paperQuestions = paperQuestionMapper.selectList(query);
        int size = paperQuestions.size();
        if (row > 0 && size > 0) {
//            paperQuestionMapper.deleteById(query);
            paperQuestionMapper.delete(query);
        }
        return row;
    }


}
